import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import axios from 'axios'
// 导入Element Plus图标
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 配置axios
axios.defaults.baseURL = 'http://localhost:8888/api/'
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    // 确保令牌格式正确
    config.headers['Authorization'] = `Bearer ${token}`
    console.log(`请求 ${config.url} 设置了Authorization头: Bearer ${token.substring(0, 15)}...`)
  } else {
    console.warn(`请求 ${config.url} 没有令牌!`)
  }
  return config
})

axios.interceptors.response.use(
  response => {
    // 检查是否有JWT过期标志
    if (response.headers && response.headers['x-jwt-expired'] === 'true') {
      console.log('JWT令牌已过期，需要重新登录')
      store.commit('logout')
      router.push('/login')
    }
    return response
  },
  error => {
    // 处理错误情况
    if (error.response) {
      // 检查是否有JWT过期标志
      if (error.response.headers && error.response.headers['x-jwt-expired'] === 'true') {
        console.log('JWT令牌已过期，需要重新登录')
        store.commit('logout')
        router.push('/login')
      } 
      // 如果是401未授权错误
      else if (error.response.status === 401) {
        console.log('用户未授权，需要重新登录')
        store.commit('logout')
        router.push('/login')
      }
      // 如果是403禁止访问错误
      else if (error.response.status === 403) {
        console.error('403禁止访问错误:', error.response.data)
        // 可能是令牌问题，尝试重新登录
        console.log('可能是令牌问题，尝试重新登录')
        store.commit('logout')
        router.push('/login')
      }
    }
    return Promise.reject(error)
  }
)

const app = createApp(App)

// 全局注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(store)
app.use(router)
app.use(ElementPlus, {
  locale: zhCn
})

app.config.globalProperties.$axios = axios

app.mount('#app') 